package o2o.service.order.shop;

import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import com.jinyouapp.common.utils.map.AMapModel;
import com.jinyouapp.common.utils.map.AMapUtils;
import o2o.cache.agent.AgentOrderOverTimeMemory;
import o2o.cache.agent.ShopAgentRelationMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.sys.SysCustomerCache;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.OrderOverTimeInfo;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.event.EventInfo;
import o2o.dao.PO.order.ORDER_STATUS;
import o2o.dao.PO.order.ORDER_TYPE;
import o2o.dao.PO.order.OrderInfo;
import o2o.service.delivery.DeliveryOrderSyncService;
import o2o.service.delivery.to.DeliveryFeeTO;
import o2o.service.delivery.to.DeliveryOrderStateTO;
import o2o.service.delivery.to.DeliveryOrderTO;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.order.OrderMan;
import o2o.web.actions.pay.OrderPay;
import org.apache.commons.lang.StringUtils;

import java.sql.SQLException;

/**
 *
 */
public class ShopOrderService {

    // 使用dcl 模式
    private ShopOrderService() {
    }

    private static ShopOrderService instance = null;

    public static ShopOrderService getInstance() {
        if (instance == null) {
            synchronized (ShopOrderService.class) {
                if (instance == null) {
                    instance = new ShopOrderService();
                }
            }
        }
        return instance;
    }

    // 对接第三方下配送单
    public boolean sendDeliverOrderData(String sysAppKey, OrderInfo orderInfo, boolean isRegisterAutoEvent) {
        // 获取配送方式
        OrderOverTimeInfo orderDeliveryInfo = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(ShopAgentRelationMemory.getInstance().getAgentByShopId(orderInfo.getShopId()));

        if (SYS_SETTINGS.IS_OTHER_POST == 2 && orderDeliveryInfo != null && StringUtils.isNotEmpty(orderDeliveryInfo.getDeliveryType())
                && !orderDeliveryInfo.getDeliveryType().equals("sys")) {
            System.out.println("发送了订单--->" + orderInfo.getOrderNo());
            // 非外卖订单 自取单  商家自配送单 不会推送给哒哒
            if ((orderInfo.getOrderType() != ORDER_TYPE.SHOP_GOODS) || orderInfo.getIsZiQu() == 1 || orderInfo.getShopSelfPost() == 1) {
                return false;
            }
            if (StringUtils.isEmpty(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }


            DeliveryOrderTO to = new DeliveryOrderTO();
            to.setSysCustomer(sysAppKey).setBuyerAddr(orderInfo.getAddress())
                    .setOrderNo(orderInfo.getOrderNo())
                    .setPlateform(orderDeliveryInfo.getDeliveryType())
                    .setDeliveryNo(orderInfo.getOrderNo())
                    .setShopId(orderInfo.getShopId() + "")
                    .setUsername(orderInfo.getUsername())
                    .setPrepayState(0)
                    .setOrderPrice(orderInfo.getTotalPrice())
                    .setBuyerName(orderInfo.getBuyer())
                    .setBuyerPhone(orderInfo.getTelephone())
                    .setBuyerLat(orderInfo.getLat())
                    .setBuyerLng(orderInfo.getLng())
                    .setProv(orderInfo.getProvince())
                    .setCity(orderInfo.getCity())
                    .setCounty(orderInfo.getCounty())
                    .setInfo(orderInfo.getNote());
            to.setFromAddress(orderInfo.getShopAddress())
                    .setFromLatitude(orderInfo.getShopLat())
                    .setFromLongitude(orderInfo.getShopLng())
                    .setFromMobile(orderInfo.getShopPhone())
                    .setFromSenderName(orderInfo.getShopName())
                    .setInfo(orderInfo.getPreDayNo() + " " + (ValidateUtil.isAbsList(orderInfo.getGoods()) ? orderInfo.getGoods().get(0).getName() : ""));
            to.setPayMoney(orderInfo.getTotalPrice()).setTotalMoney(orderInfo.getTotalMoney());
            try {
                if (StringUtils.isEmpty(to.getProv()) || StringUtils.isEmpty(to.getCity()) || StringUtils.isEmpty(to.getCounty())) {
                    AMapModel aMapModel = AMapUtils.getAddressByLngAndLat(orderInfo.getLat(), orderInfo.getLng());
                    if (aMapModel != null) {
                        if (StringUtils.isEmpty(to.getProv())) {
                            to.setProv(aMapModel.getProvince());
                        }
                        if (StringUtils.isEmpty(to.getCity())) {
                            to.setCity(aMapModel.getCity());
                        }
                        if (StringUtils.isEmpty(to.getCounty())) {
                            to.setCounty(aMapModel.getCounty());
                        }
                    }
                }
                DeliveryFeeTO deliveryFeeTO = DeliveryOrderSyncService.getInstance().sendDeliverData(to.getPlateform(), to);
                if (deliveryFeeTO != null && deliveryFeeTO.getState() == 1) {
                    StringBuffer sql = new StringBuffer();
                    sql.append("update ").append(PojoTables.OrderInfo)
                            .append(" set fcDeliveryPrice =").append(deliveryFeeTO.getDeliverFee())
                            .append(" ,isOtherPost = 1, otherPostState = 1 ")
                            .append(" where orderNo = '").append(orderInfo.getOrderNo()).append("' and delFlag = 0");
                    try {
                        UserDaoSql.getInstance().executeBySql(sql.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //
                    OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
                    return true;
                } else {
                    StringBuffer sql = new StringBuffer();
                    sql.append("update ").append(PojoTables.OrderInfo)
                            .append(" set isOtherPost = 1, otherPostState = -1 ")
                            .append(" where orderNo = '").append(orderInfo.getOrderNo()).append("' and delFlag = 0");
                    try {
                        UserDaoSql.getInstance().executeBySql(sql.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //
                    OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
                    createEvent(sysAppKey, orderInfo.getOrderNo(), isRegisterAutoEvent, EventInfo.EVENT_TYPE_SUB_DELIVERY_ORDER);
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                createEvent(sysAppKey, orderInfo.getOrderNo(), isRegisterAutoEvent, EventInfo.EVENT_TYPE_SUB_DELIVERY_ORDER);
                return false;
            }
        }
        return false;
    }

    // 取消订单
    public boolean cancelDeliveryOrderData(String sysAppKey, OrderInfo orderInfo, boolean isRegisterAutoEvent) {
        System.out.println("取消了订单--->" + orderInfo.getOrderNo());
        if (SYS_SETTINGS.IS_OTHER_POST == 2) {
            // 非外卖订单 自取单  商家自配送单 不会推送给哒哒
            if ((orderInfo.getOrderType() != ORDER_TYPE.SHOP_GOODS) || orderInfo.getIsZiQu() == 1 || orderInfo.getShopSelfPost() == 1) {
                return false;
            }
            if (StringUtils.isEmpty(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }
            // 先查询是否 --- 取消了
            DeliveryOrderStateTO queryStateTO = null;
            try {
                queryStateTO = DeliveryOrderSyncService.getInstance().queryDeliveryState(null, sysAppKey, orderInfo.getOrderNo());
            } catch (Exception e) {
                if (StringUtils.isNotEmpty(e.getMessage()) && e.getMessage().contains("订单不存在")) {
                    return true;
                }
                createEvent(sysAppKey, orderInfo.getOrderNo(), isRegisterAutoEvent, EventInfo.EVENT_TYPE_CANCEL_DELIVERY_ORDER);
                e.printStackTrace();
            }
            if (queryStateTO != null && ValidateUtil.isNotNull(queryStateTO.getOrderStatus()) && queryStateTO.getOrderStatus().equalsIgnoreCase(DeliveryOrderTO.Order_STATUS_CANCEL)) {
                return true;
            }
            // 取消
            try {
                DeliveryOrderSyncService.getInstance().cancelDeliveryOrder(DeliveryOrderSyncService.DELIVERY_PLATEFORM_DADA, sysAppKey, orderInfo.getOrderNo(), orderInfo.getCancelReason());
            } catch (Exception e) {
                e.printStackTrace();
                createEvent(sysAppKey, orderInfo.getOrderNo(), isRegisterAutoEvent, EventInfo.EVENT_TYPE_CANCEL_DELIVERY_ORDER);
                return false;
            }
            return true;
        }
        return true;
    }

    // 查询订单
    public DeliveryOrderStateTO queryDeliveryOrderState(String sysAppKey, String orderNo) {
        if (ValidateUtil.isNull(orderNo)) {
            return null;
        }
        if (ValidateUtil.isNull(sysAppKey)) {
            sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
        }
        DeliveryOrderStateTO queryStateTO = null;
        try {
            queryStateTO = DeliveryOrderSyncService.getInstance().queryDeliveryState(null, sysAppKey, orderNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return queryStateTO;
    }

    // 创建 事件 让其自动发送
    private void createEvent(String sysAppKey, String orderNo, boolean isRegisterAutoEvent, String eventType) {
        if (isRegisterAutoEvent) {

        }
    }


    // 订单状态回调通知
    public void dealDeliveryOrderState(DeliveryOrderStateTO orderStateTO, boolean isAutoQuery) throws Exception {
        if (ValidateUtil.isNull(orderStateTO.getOrderStatus()) || ValidateUtil.isNull(orderStateTO.getOrderNo())) {
            throw new Exception("信息不完整");
        }
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderStateTO.getOrderNo());
        if (orderInfo == null) {
            System.out.println("订单回调,订单不存在---->" + orderStateTO.getOrderNo());
            throw new Exception("订单信息不存在");
        }
        if (DeliveryOrderTO.Order_STATUS_WAIT_ACCETP.equals(orderStateTO.getOrderStatus())) {

        } else if (DeliveryOrderTO.Order_STATUS_WAIT_FETCH.equals(orderStateTO.getOrderStatus())) {
            if (isAutoQuery) {
                return;
            }
            if ((ORDER_STATUS.SHOP_SURE == orderInfo.getOrderStatus() || ORDER_STATUS.POSTMAN_REFUSED == orderInfo.getOrderStatus() && (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SHOP_GOODS - orderInfo.getOrderType()))) {
                // 更新订单状态
                StringBuffer sql = new StringBuffer();
                sql.append("update ").append(PojoTables.OrderInfo)
                        .append(" set postmanUsername ='").append(orderStateTO.getDeliveryPhone()).append("'")
                        .append(" ,postmanPhone ='").append(orderStateTO.getDeliveryPhone()).append("'")
                        .append(", postmanName ='").append(orderStateTO.getDeliveryName()).append("'");

                if (ValidateUtil.isNotNull(orderStateTO.getAcceptTime())) {
                    sql.append(", postmanSureTime = ").append(DateUtils.sdfDateTime.get().parse(orderStateTO.getAcceptTime()).getTime());
                }
                sql.append(" where orderNo ='").append(orderInfo.getOrderNo()).append("'").append(" and delFlag = 0");
                UserDaoSql.getInstance().executeBySql(sql.toString());
                //
                OrderMan.modifyOrderStatus("dada", orderInfo.getOrderNo(), ORDER_STATUS.POSTMAN_SURE, "", "");
                OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
            }
        } else if (DeliveryOrderTO.Order_STATUS_ARRIVE_SHOP.equals(orderStateTO.getOrderStatus())) {
            if (isAutoQuery) {
                return;
            }
            StringBuffer sql = new StringBuffer();
            sql.append("update ").append(PojoTables.OrderInfo)
                    .append(" set postmanUsername ='").append(orderStateTO.getDeliveryPhone()).append("'")
                    .append(" ,postmanPhone ='").append(orderStateTO.getDeliveryPhone()).append("'")
                    .append(", postmanName ='").append(orderStateTO.getDeliveryName()).append("'");
            if (ValidateUtil.isNotNull(orderStateTO.getAcceptTime())) {
                sql.append(", postmanSureTime = ").append(DateUtils.sdfDateTime.get().parse(orderStateTO.getAcceptTime()).getTime());
            }
            if (ValidateUtil.isNotNull(orderStateTO.getFetchTime())) {
                sql.append(", postmanArrShopTime =").append(DateUtils.sdfDateTime.get().parse(orderStateTO.getFetchTime()).getTime());
            }
            sql.append(" where orderNo ='").append(orderInfo.getOrderNo()).append("'").append(" and delFlag = 0");
            UserDaoSql.getInstance().executeBySql(sql.toString());
            OrderMan.modifyOrderStatus("dada", orderInfo.getOrderNo(), ORDER_STATUS.POSTMAN_DAODIAN, "", "");
            OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
        } else if (DeliveryOrderTO.Order_STATUS_DELIVERING.equals(orderStateTO.getOrderStatus())) {
            if (isAutoQuery) {
                return;
            }
            StringBuffer sql = new StringBuffer();
            sql.append("update ").append(PojoTables.OrderInfo)
                    .append(" set postmanUsername ='").append(orderStateTO.getDeliveryPhone()).append("'")
                    .append(" ,postmanPhone ='").append(orderStateTO.getDeliveryPhone()).append("'")
                    .append(", postmanName ='").append(orderStateTO.getDeliveryName()).append("'");
            if (ValidateUtil.isNotNull(orderStateTO.getAcceptTime())) {
                sql.append(", postmanSureTime = ").append(DateUtils.sdfDateTime.get().parse(orderStateTO.getAcceptTime()).getTime());
            }
            if (ValidateUtil.isNotNull(orderStateTO.getFetchTime())) {
                sql.append(", postmanArrShopTime =").append(DateUtils.sdfDateTime.get().parse(orderStateTO.getFetchTime()).getTime());
            }
            if (ValidateUtil.isNotNull(orderStateTO.getFetchTime())) {
                sql.append(", postmanPullTime =").append(DateUtils.sdfDateTime.get().parse(orderStateTO.getFetchTime()).getTime());
            }
            sql.append(" where orderNo ='").append(orderInfo.getOrderNo()).append("'").append(" and delFlag = 0");
            UserDaoSql.getInstance().executeBySql(sql.toString());
            OrderMan.modifyOrderStatus("dada", orderInfo.getOrderNo(), ORDER_STATUS.POSTMAN_PULL_GOODS, "", "");
            OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
        } else if (DeliveryOrderTO.Order_STATUS_DONE.equals(orderStateTO.getOrderStatus())) {
            StringBuffer sql = new StringBuffer();
            sql.append("update ").append(PojoTables.OrderInfo)
                    .append(" set postmanUsername ='").append(orderStateTO.getDeliveryPhone()).append("'")
                    .append(" ,postmanPhone ='").append(orderStateTO.getDeliveryPhone()).append("'")
                    .append(", postmanName ='").append(orderStateTO.getDeliveryName()).append("'");
            if (ValidateUtil.isNotNull(orderStateTO.getAcceptTime())) {
                sql.append(", postmanSureTime = ").append(DateUtils.sdfDateTime.get().parse(orderStateTO.getAcceptTime()).getTime());
            }
            if (ValidateUtil.isNotNull(orderStateTO.getFetchTime())) {
                sql.append(", postmanArrShopTime =").append(DateUtils.sdfDateTime.get().parse(orderStateTO.getFetchTime()).getTime());
            }
            if (ValidateUtil.isNotNull(orderStateTO.getFetchTime())) {
                sql.append(", postmanPullTime =").append(DateUtils.sdfDateTime.get().parse(orderStateTO.getFetchTime()).getTime());
            }
            if (ValidateUtil.isNotNull(orderStateTO.getFinishTime())) {
                sql.append(", postmanFinishTime =").append(DateUtils.sdfDateTime.get().parse(orderStateTO.getFinishTime()).getTime());
            }
            sql.append(" where orderNo ='").append(orderInfo.getOrderNo()).append("'").append(" and delFlag = 0");
            UserDaoSql.getInstance().executeBySql(sql.toString());
            OrderMan.modifyOrderStatus("dada", orderInfo.getOrderNo(), ORDER_STATUS.POSTMAN_FINISH, "", "");
            OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
            ResultInfo resultInfo = OrderPay.distributeMoney(orderInfo, orderInfo.getOrderNo(), "dada");
            if (resultInfo != null && resultInfo.isSuccess()) {

            } else {
                System.out.println("分成失败---/>");
                throw new Exception(resultInfo.getMessage());
            }
        } else if (DeliveryOrderTO.Order_STATUS_CANCEL.equals(orderStateTO.getOrderStatus())) {
            StringBuffer sql = new StringBuffer();
            sql.append("update ").append(PojoTables.OrderInfo)
                    .append(" set deductMoney =").append(orderStateTO.getDeductFee())
                    .append(" where orderNo = '").append(orderInfo.getOrderNo()).append("'");
            UserDaoSql.getInstance().executeBySql(sql.toString());
            OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
        }
    }

    // 订单商家备注
    public void shopNote(String shopNote, String orderNo) throws SQLException {
        if (StringUtils.isNotBlank(shopNote) && StringUtils.isNotBlank(orderNo)) {
            OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
            if (orderInfo != null) {
                orderInfo.setShopNote(shopNote);
                UserDaoSql.getInstance().updateObj(PojoTables.OrderInfo, orderInfo, "orderNo", orderNo);

                OrderInfoMemory.getInstance().run();
            }
        }
    }
}
